<template>
  <!-- 设备详情 -->
  <view class="content bg-white">
    <!-- 设备状态说明 -->
    <view class="box-select flex flex-y-center bg-white fz28">
      <view
        class="flex1 flex flex-y-center flex-x-center"
        v-for="item in state.cellStatusOptions"
        :key="item.value"
      >
        <text class="dot" :class="item.class"></text>
        {{ item.text }}
      </view>
    </view>

    <!-- 柜子列表 -->
    <view class="list flex-wrap flex-x-center">
      <template v-for="item in state.dataSource" :key="item.index">
        <view
          class="item fff"
          :class="
            item.id === state.cellId
              ? 'cur'
              : $filter.filterDictText(state.cellStatusOptions, item.cellStatus)
          "
          @click="cellClick(item)"
        >
          {{ item.otherName }}
        </view>
      </template>
    </view>

    <!-- 二维码 -->
    <view class="box-ecode">
      <image
        class="img"
        :src="state.qrcode"
        mode="aspectFit"
        :show-menu-by-longpress="true"
      ></image>
      <view class="btn-box mt30"
        ><button class="btn main-bgColor fz28 fff" @click="saveAlbum">
          下载二维码
        </button></view
      >
    </view>

    <!-- 操作按钮 -->
    <view class="fixed-btn-box t-c">
      <view
        class="btn-box flex flex-x-between flex-y-center bg-white fz28 gray9"
      >
        <view class="item" @click="openLock">
          <sw-icons icon="icon-mima1" size="34" color="#096"></sw-icons>
          <view class="mt10">开锁</view>
        </view>
        <view class="item" @click="openLockAll">
          <sw-icons icon="icon-mima1" size="34" color="#f00"></sw-icons>
          <view class="mt10">全部开锁</view>
        </view>
        <view class="item" @click="checkStatus">
          <sw-icons icon="icon-tanhao" size="34" color="#ffa200"></sw-icons>
          <view class="mt10">查询状态</view>
        </view>
        <view class="item" @click="onSet">
          <sw-icons icon="icon-shezhi" size="34" color="#487fff"></sw-icons>
          <view class="mt10">设置</view>
        </view>
        <view class="item" @click="onClear">
          <sw-icons icon="icon-qingli" size="34" color="#096"></sw-icons>
          <view class="mt10">清柜</view>
        </view>
        <view class="item" @click="onClearAll">
          <sw-icons icon="icon-qingli" size="34" color="#f00"></sw-icons>
          <view class="mt10">一键清柜</view>
        </view>
      </view>
    </view>

    <!-- 设置弹窗 -->
    <uni-popup ref="popupRef" type="center">
      <view class="popup popup-cell bg-white">
        <view class="tit fz36 t-c">请选择柜子状态</view>
        <view class="ct"
          ><uni-data-select
            v-model="state.cellStatus"
            :localdata="state.cellStatusOptions"
            :clear="false"
            placeholder="请选择"
          ></uni-data-select
        ></view>
        <view class="btn-box mt50 flex t-c fz34">
          <view class="flex1 btn-gray" @click="popopClose(popupRef)">取消</view>
          <view class="flex1 main-bgColor fff" @click="onSure">确定</view>
        </view>
      </view>
    </uni-popup>

    <!-- 提示占用柜门信息弹窗 -->
    <uni-popup ref="popupCellRef" type="center">
      <view class="popup popup-cell bg-white">
        <view class="tit fz36 t-c">系统提示</view>
        <view class="ct">
          <view class="item">手机号码：{{ state.cellInfo.storageMobile }}</view>
          <view class="item">存包密码：{{ state.cellInfo.storagePwd }}</view>
          <view class="item t-c">
            确认要打开
            <text class="blue">{{ state.cellInfo.otherName }}</text>
            柜门?
          </view>
        </view>
        <view class="btn-box mt50 flex t-c fz34">
          <view class="flex1 btn-gray" @click="popopClose(popupCellRef)"
            >取消</view
          >
          <view class="flex1 main-bgColor fff" @click="onCellSure">确定</view>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, reactive, getCurrentInstance } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import {
  getCellList,
  openCellById,
  cleanCellById,
  machineDetails,
  editCell,
  initDictOptions,
  cellCheckStatus,
  getCellOrder,
} from "@/common/js/getData.js";

const { proxy } = getCurrentInstance();
const state = reactive({
  isSend: false,
  cellStatus: "",
  id: "",
  deviceId: "",
  cellId: "",
  dataSource: [],
  qrcode: "",
  cellStatusOptions: [],
  cellInfo: {
    storageMobile: "",
    storagePwd: "",
    otherName: "",
  },
});

const colorArr = ["bg-blue", "bg-orange", "bg-red", "bg-blue-light"];

const popupRef = ref(null);
const popupCellRef = ref(null);

// 初始化数据字典
const initDictConfig = () => {
  //初始化字典 - 格子状态
  initDictOptions("cellStatus", {}, { showLoad: false }).then((res) => {
    if (res.success) {
      state.cellStatusOptions = res.result.map((item, index) => {
        const obj = item;
        obj.class = colorArr[index];
        return obj;
      });
    }
  });
};

const loadData = () => {
  getCellList({ deviceId: state.deviceId, pageSize: 1000 }).then((res) => {
    if (res.success) {
      state.dataSource = res.result.records;
    }
  });
  machineDetails({ id: state.id }, { showLoad: false }).then((res) => {
    state.qrcode = res.result.qrCode;
  });
};

// 页面加载完成
onLoad(async (option) => {
  await proxy.$onLaunched;
  state.deviceId = option.deviceId;
  state.id = option.id;
  initDictConfig();
  loadData();
});

// 关闭弹窗
const popopClose = (e) => {
  e.close();
};

// 点击柜门
const cellClick = (item) => {
  state.cellId = item.id;
  if (item.cellStatus === "1") {
    getCellOrder({ id: item.id }).then((res) => {
      console.log(res, "res");
      const { result } = res;
      state.cellInfo = {
        storageMobile: result.storageMobile,
        storagePwd: result.storagePwd,
        otherName: item.otherName,
      };
      popupCellRef.value.open();
    });
  }
};

// 确定
const onSure = () => {
  state.isSend = true;
  const data = {
    id: state.cellId,
    cellStatus: state.cellStatus,
  };
  editCell(data)
    .then((res) => {
      uni.showToast({
        title: res.message,
      });
      popopClose(popupRef.value);
      state.cellStatus = "";
      state.cellNum = "";
      setTimeout(() => {
        loadData();
      }, 1000);
    })
    .finally(() => {
      setTimeout(() => {
        state.isSend = false;
      }, 1000);
    });
};

// 占用柜门弹窗确定开锁
const onCellSure = () => {
  state.isSend = true;
  openCellById([state.cellId])
    .then((res) => {
      uni.showToast({
        title: res.message,
      });
      setTimeout(() => {
        loadData();
      }, 1000);
    })
    .finally(() => {
      setTimeout(() => {
        state.isSend = false;
      }, 1000);
    });
};

// 开锁
const openLock = (e) => {
  if (state.isSend) return;
  if (!state.cellId) {
    uni.showToast({
      icon: "none",
      title: "请选择一个柜门",
    });
    return;
  }
  uni.showModal({
    title: "提示",
    content: "是否确定开锁？",
    success: function (res) {
      if (res.confirm) {
        state.isSend = true;
        openCellById([state.cellId])
          .then((res) => {
            uni.showToast({
              title: res.message,
            });
            setTimeout(() => {
              loadData();
            }, 1000);
          })
          .finally(() => {
            setTimeout(() => {
              state.isSend = false;
            }, 1000);
          });
      }
    },
  });
};

// 全部开锁
const openLockAll = (e) => {
  if (state.isSend) return;
  uni.showModal({
    title: "提示",
    content: "是否确认全开锁",
    success: function (res) {
      if (res.confirm) {
        state.isSend = true;
        const ids = state.dataSource.map((item) => {
          return item.id;
        });
        openCellById(ids)
          .then((res) => {
            uni.showToast({
              title: res.message,
            });
          })
          .finally(() => {
            state.isSend = false;
          });
      }
    },
  });
};

// 查询状态
const checkStatus = (e) => {
  if (state.isSend) return;
  if (!state.cellId) {
    uni.showToast({
      icon: "none",
      title: "请选择一个柜门",
    });
    return;
  }
  state.isSend = true;
  cellCheckStatus({ id: state.cellId })
    .then((res) => {
      uni.showToast({
        title: res.message,
      });
      setTimeout(() => {
        loadData();
      }, 1000);
    })
    .finally(() => {
      setTimeout(() => {
        state.isSend = false;
      }, 1000);
    });
};

// 设置
const onSet = (e) => {
  if (state.isSend) return;
  if (!state.cellId) {
    uni.showToast({
      icon: "none",
      title: "请选择一个柜门",
    });
    return;
  }
  popupRef.value.open();
};

// 清柜
const onClear = (e) => {
  if (state.isSend) return;
  if (!state.cellId) {
    uni.showToast({
      icon: "none",
      title: "请选择一个柜门",
    });
    return;
  }
  uni.showModal({
    title: "提示",
    content: "是否结束柜门订单？",
    success: function (res) {
      if (res.confirm) {
        state.isSend = true;
        cleanCellById([state.cellId])
          .then((res) => {
            uni.showToast({
              title: res.message,
            });
            setTimeout(() => {
              loadData();
            }, 1000);
          })
          .finally(() => {
            setTimeout(() => {
              state.isSend = false;
            }, 1000);
          });
      }
    },
  });
};

// 一键清柜
const onClearAll = (e) => {
  if (state.isSend) return;
  uni.showModal({
    title: "提示",
    content: "是否一键清柜",
    success: function (res) {
      if (res.confirm) {
        state.isSend = true;
        const ids = state.dataSource.map((item) => {
          return item.id;
        });
        cleanCellById(ids)
          .then((res) => {
            uni.showToast({
              title: res.message,
            });
            setTimeout(() => {
              loadData();
            }, 1000);
          })
          .finally(() => {
            setTimeout(() => {
              state.isSend = false;
            }, 1000);
          });
      }
    },
  });
};

// 下载图片
const saveImageToPhotosAlbum = () => {
  const base64 = state.qrcode.replace(/^data:image\/jpg;base64,/, ""); //去掉data:image/png;base64,
  const filePath = wx.env.USER_DATA_PATH + "/qrcode.png";
  uni.getFileSystemManager().writeFile({
    filePath: filePath, //创建一个临时文件名
    data: base64, //写入的文本或二进制数据
    encoding: "base64", //写入当前文件的字符编码
    success: (res) => {
      uni.saveImageToPhotosAlbum({
        filePath: filePath,
        success: function () {
          uni.showToast({
            title: "下载成功",
          });
        },
        fail: function (err) {
          uni.showToast({
            icon: "none",
            title: "下载失败，可长按二维码识别或保存",
          });
        },
      });
    },
    fail: (err) => {
      uni.showToast({
        icon: "none",
        title: "下载失败，可长按二维码识别或保存",
      });
    },
  });
};

// 获取是否有保存相册权限
const saveAlbum = () => {
  //获取权限保存相册
  uni.getSetting({
    //获取用户的当前设置
    success: (res) => {
      // console.log("获取权限",res);
      if (res.authSetting["scope.writePhotosAlbum"]) {
        //验证用户是否授权可以访问相册
        saveImageToPhotosAlbum();
      } else {
        uni.authorize({
          //如果没有授权，向用户发起请求
          scope: "scope.writePhotosAlbum",
          success: () => {
            saveImageToPhotosAlbum();
          },
          fail: () => {
            uni.showToast({
              title: "请打开保存相册权限，再点击保存相册分享",
              icon: "none",
            });
            setTimeout(() => {
              uni.openSetting({
                //调起客户端小程序设置界面,让用户开启访问相册
                success: (res2) => {
                  // console.log(res2.authSetting)
                },
              });
            }, 3000);
          },
        });
      }
    },
  });
};
</script>

<style lang="less" scoped>
@import url("@/common/less/common.less");

.bg-blue {
  background: #03a9f4 !important;
}

.list {
  padding: 20rpx 0;
  .item {
    width: 160rpx;
    margin: 10rpx;
    border-radius: 20rpx;
    box-shadow: 0 5rpx 10rpx rgba(#000, 0.1);
    line-height: 120rpx;
    text-align: center;
    &.cur {
      color: @gray3 !important;
      background: @yellow;
    }
  }
}

.box-select {
  padding: 20rpx 10rpx;
  .flex1 {
    .dot {
      display: block;
      width: 30rpx;
      height: 30rpx;
      margin-right: 10rpx;
      border-radius: 50%;
    }
  }
}

.box-ecode {
  padding: 60rpx 0;
  width: 470rpx;
  margin: 0 auto;
  .img {
    width: 470rpx;
    height: 470rpx;
  }
}

.popup-cell {
  .tit {
    padding-bottom: 10rpx;
  }
  .ct {
    padding: 0 30rpx;
    .item {
      padding: 30rpx 0;
    }
  }
  .btn-gray {
    background: #f0f0f0;
  }
}
</style>
